@file:JvmMultifileClass
@file:JvmName("LifecycleThreadResult")

package hos.thread.lifecycle


/**
 * <p>Title: ThreadResult </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2023/7/31 14:04
 * @version : 1.0
 */
sealed class LifecycleThreadResult {

    //定义请求成功
    data class SUCCESS<T>(val result: T) : LifecycleThreadResult()

    //定义请求失败
    data class FAIL(val throwable: Throwable, val name: String) :
        LifecycleThreadResult()

    //定义请求取消
    data class CANCEL(val tip: String = "取消") :
        LifecycleThreadResult()

    //定义请求开始
    data class START(val tip: String = "开始") :
        LifecycleThreadResult()

    //定义请求进行中
    data class RUNNING(val progress: Double = 0.0) :
        LifecycleThreadResult()


    @Suppress("UNCHECKED_CAST")
    fun <T> doSuccess(success: T?.() -> Unit) {
        if (this is SUCCESS<*>) {
            if (result is Unit?) {
                success(null)
                return
            }
            success(result as T?)
        }
    }

    fun doStart(start: String.() -> Unit) {
        if (this is START) {
            start(tip)
        }
    }

    fun doCancel(cancel: String.() -> Unit) {
        if (this is CANCEL) {
            cancel(tip)
        }
    }

    fun doFail(fail: Throwable.(name: String) -> Unit) {
        if (this is FAIL) {
            fail(throwable, name)
        }
    }

    fun doRunning(running: Double.() -> Unit) {
        if (this is RUNNING) {
            running(progress)
        }
    }
}
